﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Rabbit.API.Application.Command.Goods;

namespace Rabbit.API.Application.Handler.Goods
{
    public class GoodsDelHandler:IRequestHandler<GoodsDelCommand,APIResult<int>>
    {
        private readonly IRepository<GoodsModel> goodsway;
        private readonly IMapper mapper;
        private readonly ILogger<GoodsGetHandler> log;

        public GoodsDelHandler(IRepository<GoodsModel> goodsway, IMapper mapper, ILogger<GoodsGetHandler> log)
        {
            this.goodsway = goodsway;
            this.mapper = mapper;
            this.log = log;
        }

        /// <summary>
        /// 商品信息删除
        /// </summary>
        /// <param name="request">主键</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        public async Task<APIResult<int>> Handle(GoodsDelCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            try
            {
                var goods = goodsway.GetAll().FirstOrDefault(x=>x.Id==request.Id);
                goods.IsDel = true;
                var result = await goodsway.Updateway(goods);
                if(result>0)
                {
                    res.Num = StateCode.OK;
                    res.Message = $"商品信息删除成功";
                    res.Data = result;
                }
                else
                {
                    res.Num = StateCode.Fail;
                    res.Message = $"商品信息删除失败";
                }
                return res;
            }
            catch (Exception ex)
            {
                log.LogError($"发生异常{ex.Message}");
                throw;
            }
        }
    }
}
